package com.mk.common.aspect.log;

import com.mk.common.util.DateUtil;
import com.mk.data.dao.ApiCallLogMapper;
import com.mk.model.ApiCallLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 系统日志切面
 *
 */
@Aspect
@Component
public class SysLogAspect {
    @Resource
    ApiCallLogMapper apiCallLogMapper;


    /**
     * 这里我们使用注解的形式
     * 当然，我们也可以通过切点表达式直接指定需要拦截的package,需要拦截的class 以及 method
     * 切点表达式:   @Pointcut("execution(public * com.aop.demo.controller.*.*(..))")
     */
    @Pointcut("@annotation(com.mk.common.aspect.log.SysLog)")
    public void logPointCut() {

    }

    /**
     * 环绕通知 @Around  ， 当然也可以使用 @Before (前置通知)  @After (后置通知)
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object result = point.proceed();
        long time = System.currentTimeMillis() - beginTime;

        try {
            recordLog(point, time);
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 记录日志
     * @param joinPoint
     * @param time
     */
    private void recordLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        //请求的 类名、方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        apiCallLogMapper.insert(new ApiCallLog(1,className,methodName,time, DateUtil.getDatetimeForSql()));

        /**
         * 获取注解参数
         */
        Method method = signature.getMethod();
        SysLog s = method.getAnnotation(SysLog.class);
        System.out.println(s.value());
    }

}
